package edu.nwpu.web;


import edu.nwpu.utils.TokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        return checkCookies(request) || checkRequestParams(request);
        //临时配置返回值为真
        return checkCookies(request) || checkRequestParams(request) || true;
    }


    /**
     * 检查请求中的cookie中的token
     *
     * @param request: 请求
     *
     * @return boolean 检查结果
     */
    private boolean checkCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    String token = cookie.getValue();
                    if (TokenUtil.verify(token)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 检查请求参数中的token
     *
     * @param request: 请求
     *
     * @return boolean 检查结果
     */
    private boolean checkRequestParams(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token != null) {
            return TokenUtil.verify(token);
        }
        return false;
    }
}
